package com.liqi.web.controller.items;

import com.liqi.common.annotation.Log;
import com.liqi.common.core.controller.BaseController;
import com.liqi.common.core.domain.AjaxResult;
import com.liqi.common.core.domain.R;
import com.liqi.common.core.page.TableDataInfo;
import com.liqi.common.enums.BusinessType;
import com.liqi.common.utils.DateUtils;
import com.liqi.common.utils.poi.ExcelUtil;
import com.liqi.device.domain.DvGroup;
import com.liqi.items.domain.TCfgBranch;
import com.liqi.items.domain.TCfgSubject;
import com.liqi.items.domain.VO.TCfgBranchVO;
import com.liqi.items.service.ITCfgBranchService;
import com.liqi.items.service.ITCfgSubjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 网点Controller
 *
 * @author Lwy
 * @date 2022-04-07
 */
@RestController
@Api(tags = "网点管理2")
@RequestMapping("/items/branch")
public class TCfgBranchController extends BaseController
{
    @Autowired
    private ITCfgBranchService tCfgBranchService;

    @Autowired
    private ITCfgSubjectService tCfgSubjectService;

    /**
     * 查询网点列表
     */
    @PreAuthorize("@ss.hasPermi('items:branch:list')")
    @GetMapping("/list")
    @ApiOperation("网点列表")
    public TableDataInfo list(TCfgBranch tCfgBranch)
    {
        if(tCfgBranch.getBranchCode()!=null||tCfgBranch.getBranchName()!=null||tCfgBranch.getRegionId()!=null){
            tCfgBranch.setParentCode(null);
        }

        if("".equals(tCfgBranch.getBranchCode())&&"".equals(tCfgBranch.getBranchName())&&tCfgBranch.getRegionId()==null){
            tCfgBranch.setBranchCode(null);
            tCfgBranch.setBranchName(null);
            tCfgBranch.setParentCode("0");
        }


        startPage();
        List<TCfgBranch> list = tCfgBranchService.selectTCfgBranchList(tCfgBranch);
        return getDataTable(list);
    }

    /**
     * 导出网点列表
     */
    @PreAuthorize("@ss.hasPermi('items:branch:export')")
    @Log(title = "网点", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出网点列表")
    public void export(HttpServletResponse response, TCfgBranch tCfgBranch)
    {
        List<TCfgBranch> list = tCfgBranchService.selectTCfgBranchList(tCfgBranch);
        ExcelUtil<TCfgBranch> util = new ExcelUtil<TCfgBranch>(TCfgBranch.class);
        util.exportExcel(response, list, "网点数据");
    }

    /**
     * 获取网点详细信息
     */
    @PreAuthorize("@ss.hasPermi('items:branch:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取网点详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        TCfgBranchVO tCfgBranchVO = tCfgBranchService.selectTCfgBranchById(id);
        System.out.println(tCfgBranchVO);
        return AjaxResult.success(tCfgBranchVO);
    }

    /**
     * 新增网点
     */
    @PreAuthorize("@ss.hasPermi('items:branch:add')")
    @Log(title = "网点", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增网点")
    public AjaxResult add(@RequestBody TCfgBranch tCfgBranch)
    {
        TCfgBranch tCfgBranch1 = tCfgBranchService.selectTCfgBranchByBranchName(tCfgBranch.getBranchName());
       if(tCfgBranch1!=null){
           return AjaxResult.error("网点名称重复");
       }
        if(tCfgBranch.getParentCode()==null){
            tCfgBranch.setParentCode("0");
        }
        tCfgBranch.setCreateBy(getUsername());
        tCfgBranch.setCreateTime(DateUtils.getNowDate());
        tCfgBranch.setUpdateBy(getUsername());
        tCfgBranch.setUpdateTime(DateUtils.getNowDate());

        tCfgBranch.setStatus(0);
        if(!tCfgBranch.getParentCode().equals("0")){
            TCfgBranch tCfgBranchParent = tCfgBranchService.selectTCfgBranchListByBranchCode(tCfgBranch.getParentCode());

            // 父节点的祖籍列表
            String Pancestors = tCfgBranchParent.getRegionAncestors();
            // 父节点branchCode
//            String regionIdParent = tCfgBranchParent.getRegionId();
            StringBuilder sb = new StringBuilder();
            sb.append(Pancestors).append("," + tCfgBranch.getRegionId());
            tCfgBranch.setRegionAncestors(sb.toString());
            tCfgBranchService.updateTCfgBranch(tCfgBranchParent);
        }
        return toAjax(tCfgBranchService.insertTCfgBranch(tCfgBranch));
    }
    /**
     * 修改网点
     */
    @PreAuthorize("@ss.hasPermi('items:branch:edit')")
    @Log(title = "网点", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改网点")
    public AjaxResult edit(@RequestBody TCfgBranch tCfgBranch)
    {


        if(tCfgBranch.getParentCode()==null){
            tCfgBranch.setParentCode("0");
        }
      if  (tCfgBranch.getParentCode().equals(tCfgBranch.getBranchCode())){
            return  AjaxResult.error("请勿将本网点修改到本网点下级");
    }
//        TCfgBranch tCfgBranch2 = tCfgBranchService.selectTCfgBranchListByBranchCode(tCfgBranch.getBranchCode());
//      if(tCfgBranch2!=null){
//          return AjaxResult.error("已有网点编码，请误重复添加");
//      }
//
//        String branchCode = tCfgBranch.getBranchCode();
//        String parentCode = tCfgBranch.getParentCode();
//        String oldBranchCode = tCfgBranch.getOldBranchCode();
//        TCfgBranch tCfgBranchOld = tCfgBranchService.selectTCfgBranchListByBranchCode(oldBranchCode);
//        TCfgBranch tCfgBranch1 = tCfgBranchService.selectTCfgBranchListByBranchCode(parentCode);
//        List<TCfgBranch> tCfgBranches = tCfgBranchService.selectTCfgBranchListByParentCode(branchCode);
//        if(tCfgBranches.size()==0){
//            tCfgBranch.setHaveChildren("0");
//        }else {
//            tCfgBranch.setHaveChildren("1");
//        }
//        if(!parentCode.equals("0")){
//            tCfgBranch1.setHaveChildren("1");
//            tCfgBranchService.updateTCfgBranch(tCfgBranch1);
//        }
//        tCfgBranchService.updateTCfgBranch(tCfgBranch);
//        if(!oldBranchCode.equals("0")){
//            if(tCfgBranchService.selectTCfgBranchListByParentCode(oldBranchCode).size()!=0){
//                tCfgBranchOld.setHaveChildren("1");
//            }else {
//                tCfgBranchOld.setHaveChildren("0");
//            }
//            tCfgBranchService.updateTCfgBranch(tCfgBranchOld);
//        }


        return toAjax(tCfgBranchService.updateTCfgBranch(tCfgBranch));
    }

    /**
     * 删除网点
     */
    @PreAuthorize("@ss.hasPermi('items:branch:remove')")
    @Log(title = "网点", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    @ApiOperation("删除网点")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        List<TCfgSubject> subjects = new ArrayList<>();
        for (Long id : ids) {
            TCfgBranchVO tCfgBranch = tCfgBranchService.selectTCfgBranchById(id);
            String branchCode = tCfgBranch.getBranchCode();
            List<TCfgSubject> tCfgSubjects = tCfgSubjectService.selectTCfgSubjectByBranchCode(branchCode);
            subjects.addAll(tCfgSubjects);
        }
        if (subjects.size() != 0) {
            for (TCfgSubject subject : subjects) {
                TCfgSubject tCfgSubject = tCfgSubjectService.selectTCfgSubjectById(subject.getId());
                if (tCfgSubject != null ) {
                    tCfgSubject.setUpdateBy(getUsername());
                    tCfgSubject.setUpdateTime(DateUtils.getNowDate());
                    tCfgSubject.setStatus(1);
                    tCfgSubjectService.updateTCfgSubject(tCfgSubject);
                }
            }
        }
        return toAjax(tCfgBranchService.deleteTCfgBranchByIds(ids));
    }


    /**
     * 获取设备投放城市
     */
    /*@PreAuthorize("@ss.hasPermi('system:region:getregion')")*/
    @GetMapping(value = "/getBranch")
    @ApiOperation("获取设备投放城市")
    public TableDataInfo getBranch(@RequestParam(value="parentCode")String parentCode)
    {
        startPage();
        List<TCfgBranchVO> list = tCfgBranchService.selectTCfgBranchListByParentCode(parentCode);
        return getDataTable(list);
    }
    @GetMapping("/data")
    public List<TCfgBranch> data( ) {

        List<TCfgBranch> data = tCfgBranchService.selectTCfgBranchData();
        return data;
    }
    @GetMapping("/getDataByParentCode")
    @ApiOperation("根据父网点编码获取下级网点信息")
    public R<List<TCfgBranchVO>> getDataByParentCode(@RequestParam(value="parentCode")String parentCode) {

        List<TCfgBranchVO> data = tCfgBranchService.selectTCfgBranchDataByParentCode(parentCode);
        return R.ok(data);
    }


}

